<template>
  <view class="store-order-details">
    <view class="status-info">
      <view class="txt">
        <span
          :class="iconStatusClass"
          class="iconfont"
          :style="{ color: themeColor, marginRight: '24rpx' }"
        ></span>
        {{ orderDetail.title || "" }}
      </view>
    </view>
    <view v-if="orderDetail.type === 'PUB_LOCAL'" class="card-address">
      <view class="address-info">
        <view class="bg"
          ><image
            src="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/39/20230306/cfc2262f-2894-49a9-961c-d2e635ae8616.png"
          ></image
        ></view>
        <view class="address">
          <view class="adTxt">
            <view class="name"
              >{{ orderDetail.delivery.userName }}
              {{ orderDetail.delivery.phone }}</view
            >
            <view class="detail">
              {{
                orderDetail.delivery.province +
                orderDetail.delivery.city +
                orderDetail.delivery.country +
                orderDetail.delivery.street +
                orderDetail.delivery.detail
              }}
            </view>
          </view>
          <view class="location"></view>
        </view>
      </view>
      <view class="getGoods-info">
        <view class="msg-info">
          <view class="li">送达时间：{{ orderDetail.appointmentTime }}</view>
          <view class="li">备注：{{ orderDetail.userRemark }}</view>
        </view>
      </view>
    </view>
    <view v-else class="card-address">
      <view class="address-info">
        <view class="bg"
          ><image
            src="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/39/20230306/cfc2262f-2894-49a9-961c-d2e635ae8616.png"
          ></image
        ></view>
        <view class="address">
          <view class="adTxt">
            <view class="name">门店地址</view>
            <view class="detail">{{ orderDetail.storeAddress }}</view>
          </view>
          <view @click="openLocationFun" class="location">
            <view class="iconfont icon-weizhi"></view>
            导航
          </view>
        </view>
      </view>
      <!-- <view v-if="orderDetail.type === 'PUB_SELF_PICKUP' && (orderDetail.orderStatus === 'UNDERWAY' || orderDetail.orderStatus === 'FINISH')" class="getGoods-info">
				<view class="qrCode">
					<image :src="require('https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/3384/20230306/99662f43-7e88-4753-82ea-229fcf2033da.png')"></image>
				</view>
				<view class="msg-info">
					<view class="li">核销码：{{orderDetail.finishTime}}</view>
					<view class="li">自提时间：{{orderDetail.finishTime}}</view>
					<view class="li">备注：不要包装。</view>
				</view>
			</view> -->
      <view class="getGoods-info">
        <view class="qrCode" v-if="orderDetail.qrcode">
          <image :src="orderDetail.qrcode"></image>
        </view>
        <view class="msg-info">
          <view v-if="orderDetail.delivery.takeNo" class="li"
            >核销码：{{ orderDetail.delivery.takeNo || "" }}</view
          >
          <view v-if="orderDetail.type === 'PUB_SELF_PICKUP'" class="li"
            >自提时间：{{ orderDetail.appointmentTime }}</view
          >
          <view
            class="li"
            v-if="
              (orderDetail.type === 'PUB_PACK' ||
                orderDetail.type === 'PUB_HALL_FOOD') &&
              orderDetail.tableNo
            "
            >桌码：{{ orderDetail.tableNo }}</view
          >
          <view class="li">备注：{{ orderDetail.userRemark || "" }}</view>
        </view>
      </view>
    </view>
    <view class="card-order-list">
      <view class="li-box">
        <view @click="handleAgain" class="top-info">
          <view class="lef">
            <view class="logo"><xh-img :src="orderDetail.logo" /></view>
            <view class="title">{{ orderDetail.storeName }}</view>
          </view>
          <view class="rig iconfont icon-xiangyoujiantou"></view>
        </view>
        <view
          v-for="(item, index) in orderDetail.items"
          :key="index"
          class="cen-info"
        >
          <view class="shop">
            <view class="img"><xh-img :src="item.coverImg" /></view>
          </view>

          <view class="conten">
            <view class="shopTxt">
              <view class="name">{{ item.title }}</view>
              <view v-if="item.skuInfo !== '[]'" class="spec">
                {{ JSON.parse(item.skuInfo) }}
              </view>
            </view>
            <view class="num">
              <view class="money">
                <span style="font-size: 20rpx">￥</span>
                {{ item.price / 100 }}
              </view>
              <view class="txt">x{{ item.num }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="card-amount">
      <view class="row">
        <view class="tit">商品小计</view>
        <view>￥{{ orderDetail.subOrderTotal }}</view>
      </view>
      <view class="row">
        <view class="tit">{{
          orderDetail.industry <= 100 ? "就餐方式" : "配送方式"
        }}</view>
        <view>
          {{
            orderDetail.type === "PUB_LOCAL"
              ? "外卖配送"
              : orderDetail.type === "PUB_HALL_FOOD"
              ? "堂食"
              : orderDetail.type === "PUB_PACK"
              ? "打包"
              : orderDetail.type === "PUB_SHOP_CONSUME"
              ? "到店消费"
              : "自提"
          }}
        </view>
      </view>
      <view v-if="orderDetail.type === 'PUB_LOCAL'" class="row">
        <view class="tit">配送费</view>
        <view>￥{{ orderDetail.deliveryFee / 100 || 0 }}</view>
      </view>
      <view
        v-if="
          orderDetail.type === 'PUB_PACK' ||
          orderDetail.type === 'PUB_SELF_PICKUP'
        "
        class="row"
      >
        <view class="tit">打包费</view>
        <view>￥{{ orderDetail.packFee / 100 || 0 }}</view>
      </view>
      <view
        class="row"
        v-if="
          orderDetail &&
          orderDetail.discountAmount &&
          orderDetail.discountAmount.amount
        "
      >
        <view class="tit">优惠</view>
        <view
          >-￥{{
            $myTool.toFixedNum(orderDetail.discountAmount.amount / 100) || 0
          }}</view
        >
      </view>
      <view class="row results">
        <view
          class="preferential"
          v-if="
            orderDetail &&
            orderDetail.discountAmount &&
            orderDetail.discountAmount.amount
          "
        >
          已优惠：￥{{
            $myTool.toFixedNum(orderDetail.discountAmount.amount / 100) || 0
          }}
        </view>
        <view class="total">
          合计：
          <span>￥{{ orderDetail.subOrderPrice }}</span>
        </view>
      </view>
    </view>
    <view class="card-order">
      <view class="row">
        <view class="tit">订单编号</view>
        <view>
          {{ orderDetail.orderNo || "" }}
          <span style="color: #cdcdcd; margin: 0 14rpx">|</span>
          <span style="color: #ffb72f" @click="copy()">复制</span>
        </view>
      </view>
      <view class="row">
        <view class="tit">下单时间</view>
        <view>{{ orderDetail.createTime }}</view>
      </view>

      <!-- 已付款 -->
      <template v-if="orderDetail.orderStatus !== 'WAITING'">
        <!-- 取消订单 -->
        <template
          v-if="
            orderDetail.orderStatus === 'CANCEL' &&
            orderDetail.title !== '已退款'
          "
        >
          <view class="row">
            <view class="tit">取消时间</view>
            <view>{{ orderDetail.cancelTime }}</view>
          </view>
        </template>
        <template v-else>
          <view class="row">
            <view class="tit">支付时间</view>
            <view>{{ orderDetail.paymentTime }}</view>
          </view>
          <view class="row">
            <view class="tit">支付方式</view>
            <view>{{
              orderDetail.payInfo.paymentMethod == 1 ? "微信支付" : "余额支付"
            }}</view>
          </view>

          <view v-if="orderDetail.deliveryTime" class="row">
            <view class="tit">配送时间</view>
            <view>{{ orderDetail.paymentTime }}</view>
          </view>
          <view v-if="orderDetail.finishTime" class="row">
            <view class="tit">完成时间</view>
            <view>{{ orderDetail.finishTime }}</view>
          </view>
          <view v-if="orderDetail.refundRecord[0].createTime" class="row">
            <view class="tit">退款时间</view>
            <view>{{ orderDetail.refundRecord[0].createTime }}</view>
          </view>
        </template>
      </template>
    </view>

    <view class="btm-info">
      <view class="lef">
        <view class="txt">
          {{
            orderDetail.orderStatus === "WAITING" ||
            (orderDetail.orderStatus === "CANCEL" &&
              orderDetail.refundAmt === 0)
              ? "应付"
              : orderDetail.refundAmt
              ? "已退"
              : "实付"
          }}：
        </view>
        <view class="money">
          <span>￥</span>
          <template v-if="orderDetail.refundAmt">
            {{ $myTool.toFixedNum(orderDetail.refundAmt / 100) }}
          </template>
          <template v-else-if="orderDetail.payInfo">
            {{ $myTool.toFixedNum(orderDetail.payInfo.payFee / 100) }}
          </template>
        </view>
      </view>
      <view v-if="orderDetail.orderStatus === 'WAITING'" class="rig">
        <button
          @click="handleCancel"
          class="againBtn"
          hover-class="hoverClass"
          :style="{ borderColor: themeColor, color: themeColor }"
        >
          取消订单
        </button>
        <button
          @click="handlePay"
          class="payBtn"
          hover-class="hoverClass"
          :style="{ backgroundColor: themeColor }"
        >
          立即支付
        </button>
      </view>
      <view v-else class="rig">
        <button
          @click="handleAgain"
          class="againBtn"
          hover-class="hoverClass"
          :style="{ borderColor: themeColor, color: themeColor }"
        >
          再来一单
        </button>

        <button
          v-if="
            orderDetail.type !== 'PUB_LOCAL' &&
            orderDetail.orderStatus === 'UNDERWAY'
          "
          @click="handleVerification"
          class="payBtn"
          hover-class="hoverClass"
          :style="{ backgroundColor: themeColor }"
        >
          已核销
        </button>
        <button
          v-if="
            orderDetail.type === 'PUB_LOCAL' &&
            (orderDetail.subStatusInt === 102 ||
              orderDetail.subStatusInt === 103)
          "
          @click="handleFinish"
          class="payBtn"
          hover-class="hoverClass"
          :style="{ backgroundColor: themeColor }"
        >
          已完成
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from "vuex";
import {
  cancel,
  confirm_receipt,
  get_order_detail,
  writeOff,
} from "@/service/api/sp-order/index";
import { getShopDetail } from "@/service/api/sp-store";
import { createQRCode } from "@/utils/createQRCode";
import { ORDER_DELIVER_METHOD, ORDER_STATE, ORDER_STATUS } from "@/const/order";

export default {
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
    ...mapState("sp-store/index", ["dineParams", "pubShopInfo"]),
  },
  data() {
    return {
      option: "",
      // 订单详情
      orderDetail: "",
      iconStatusClass: "",
      curStatusTitle: "", //如订单状态有变化，返回订单列表会刷新
      timer: null,
    };
  },
  onLoad() {
    this.getEventChannel();
  },
  destroyed() {
    // console.log("销毁了");
    clearInterval(this.timer);
  },
  methods: {
    getEventChannel() {
      const eventChannel = this.getOpenerEventChannel();
      if (JSON.stringify(eventChannel) !== "{}") {
        eventChannel.on("orderList", (res) => {
          this.option = res;
          this.initFun();
        });
      } else {
        this.option = this.$Route.query;
        this.initFun();
      }
    },

    initFun() {
      this.get_order_detailFun().then(() => {
        if (
          this.orderDetail.orderStatus === ORDER_STATE.UNDERWAY &&
          this.orderDetail.delivery?.takeNo
        ) {
          this.timer = setInterval(() => {
            this.get_order_detailFun();
          }, 1000);
        }
      });
    },
    // 复制
    copy() {
      uni.setClipboardData({
        data: this.orderDetail.orderNo,
        success: () => {
          uni.showToast({
            icon: "none",
            title: "复制成功",
          });
        },
      });
    },
    // 导航
    openLocationFun() {
      let { latitude, longitude, storeName, storeAddress } = this.orderDetail;
      this.$myTool.lookLocation(latitude, longitude, storeName, storeAddress);
    },

    // 订单详情
    async get_order_detailFun() {
      let params = {
        orderNo: this.option.data.orderNo,
      };
      const res = await get_order_detail(params);
      // console.log("订单详情", res);
      const takeNo = res?.delivery?.takeNo;
      if (takeNo) {
        const url = `type=pubUserWriteOff&takeNo=${takeNo}`;
        res.qrcode = await createQRCode(url);
        // console.log("====delivery", qrcode);
      }
      res.items.forEach((el) => {
        el.skuInfo = JSON.parse(JSON.stringify(el.skuInfo));
      });
      this.orderDetail = res;
      if (
        this.orderDetail.orderStatus === ORDER_STATE.FINISH &&
        this.orderDetail.delivery?.takeNo
      ) {
        clearInterval(this.timer);
        this.timer = null;
      }
      this.calculateFun();
      this.iconStatusClassFun();
      uni.stopPullDownRefresh();
      this.eventChannelEmit();
    },

    // 触发订单列表刷新
    eventChannelEmit() {
      if (
        this.curStatusTitle &&
        this.curStatusTitle !== this.orderDetail.title
      ) {
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit("orderStatus", { data: this.orderDetail.title });
      }
      this.curStatusTitle = this.orderDetail.title;
    },

    // 订单状态icon
    iconStatusClassFun() {
      let { orderStatus, type, refundAmt, subStatusInt } = this.orderDetail;
      this.iconStatusClass =
        orderStatus === "WAITING"
          ? "icon-daifukuan"
          : orderStatus === "UNDERWAY" &&
            type === "PUB_LOCAL" &&
            subStatusInt === 102
          ? "icon-xiuxi"
          : orderStatus === "UNDERWAY" &&
            type === "PUB_LOCAL" &&
            subStatusInt === 103
          ? "icon-peisongzhong"
          : orderStatus === "UNDERWAY" &&
            (type === "PUB_PACK" || type === "PUB_SELF_PICKUP")
          ? "icon-daitihuo"
          : orderStatus === "CANCEL" && refundAmt === 0
          ? "icon-quxiao"
          : refundAmt > 0
          ? "icon-yituikuan"
          : "icon-wancheng";
    },

    // 设置订单
    calculateFun() {
      //其他信息
      let { items, type, deliveryFee, packFee, amounts } = this.orderDetail;
      let amount = this?.orderDetail?.discountAmount?.amount || 0;
      // 商品小计
      let subtotal = 0;
      items.forEach((el) => {
        el.subPrice = el.num * (el.price / 100);
        subtotal += el.subPrice;
      });
      amounts?.forEach((v) => {
        amount += v.amount;
      });
      //商品小计
      this.orderDetail.subOrderTotal = this.$myTool.toFixedNum(subtotal);
      // 合计
      this.orderDetail.subOrderPrice = this.$myTool.toFixedNum(amount / 100);
      // if (type === "PUB_LOCAL") {
      //   this.orderDetail.subOrderPrice = this.$myTool.toFixedNum(
      //     (subtotal * 100 + deliveryFee - amount) / 100
      //   );
      // } else if (type === "PUB_PACK") {
      //   this.orderDetail.subOrderPrice = this.$myTool.toFixedNum(
      //     (subtotal * 100 + packFee - amount) / 100
      //   );
      // } else {
      //   this.orderDetail.subOrderPrice = this.$myTool.toFixedNum(
      //     (subtotal * 100 - amount) / 100
      //   );
      // }
    },

    //再来一单
    handleAgain() {
      clearInterval(this.timer);
      const pages = getCurrentPages();
      if (
        pages[pages.length - 2].route == "pages/sp-store/pages/shop-index/index"
      ) {
        uni.navigateBack({
          delta: 1,
        });
      } else {
        uni.redirectTo({
          url: `pages/sp-store/pages/shop-index/index?shopId=${this.orderDetail.pubShopId}`,
        });
      }
    },
    //去支付
    async handlePay() {
      let { orderNo, pubShopId } = this.orderDetail;
      let { storeNo } = await getShopDetail({ id: pubShopId });
      this.$pay({ xhOrderNo: orderNo, storeNo }).then((res) => {
        console.log("收银台", res);
        if (res.code === 0) {
          uni.showToast({
            title: "支付成功",
            icon: "none",
          });
          this.initFun();
        }
      });
    },
    //取消订单
    handleCancel() {
      let params = {
        orderNo: this.option.data.orderNo,
      };
      cancel(params)
        .then((res) => {
          uni.showToast({
            title: "订单取消成功",
            icon: "none",
          });
          this.initFun();
        })
        .catch((err) => {
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000,
          });
        });
    },
    // 完成
    handleFinish() {
      let params = {
        orderNo: this.option.data.orderNo,
      };
      confirm_receipt(params)
        .then((res) => {
          uni.showToast({
            title: "订单已完成",
            icon: "none",
          });
          this.initFun();
        })
        .catch((err) => {
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000,
          });
        });
    },
    // 核销
    handleVerification() {
      let params = {
        orderNoOrCode: this.option.data.orderNo,
      };
      writeOff(params)
        .then((res) => {
          uni.showToast({
            title: "订单已完成",
            icon: "none",
          });
          this.initFun();
        })
        .catch((err) => {
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000,
          });
        });
    },

    onPullDownRefresh() {
      console.log("下拉刷新");
      this.initFun();
    },
  },
};
</script>
<style>
page {
  background-color: #f7f7f7;
}
</style>
<style lang="scss" scoped>
.store-order-details {
  padding: 20rpx;
  padding-top: 0;
  box-sizing: border-box;

  .status-info {
    display: flex;
    justify-content: center;
    margin: 37rpx 0;

    .txt {
      font-size: 29rpx;
      font-weight: 500;
      color: #181818;
      margin-left: 23rpx;
      align-items: center;
      display: flex;

      .iconfont {
        font-size: 40rpx;
      }
    }
  }

  .card-address {
    background-color: white;
    border-radius: 8rpx;

    .address-info {
      position: relative;
      width: 100%;
      height: 200rpx;

      .bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .address {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 2;

        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 40rpx 23rpx;
        box-sizing: border-box;
        // background-image: url('https://img1.baidu.com/it/u=3009731526,373851691&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500');
        background-repeat: no-repeat;

        .adTxt {
          flex: 7;

          .name {
            font-size: 32rpx;
            font-weight: bold;
            color: #131313;
          }

          .detail {
            font-size: 29rpx;
            font-weight: 500;
            color: #888888;
            margin-top: 23rpx;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-box-orient: vertical;
            word-break: break-all;
          }
        }

        .location {
          flex: 1;
          text-align: center;
          font-size: 20rpx;
          font-weight: 500;
          color: #888888;

          .iconfont {
            font-size: 33rpx;
          }
        }
      }
    }

    .getGoods-info {
      display: flex;
      justify-items: flex-start;
      margin-top: 16rpx;

      .qrCode {
        width: 180rpx;
        height: 180rpx;
        border-radius: 8rpx;
        overflow: hidden;
        margin: 24rpx;
        margin-right: 0;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .msg-info {
        font-size: 29rpx;
        font-weight: 500;
        color: #131313;
        margin-left: 24rpx;
        flex: 1;
        .li {
          margin-bottom: 45rpx;
        }

        .li:nth-of-type(1) {
          margin-top: 24rpx;
        }
      }
    }
  }

  .card-order-list {
    margin-top: 20rpx;

    .li-box {
      background-color: white;
      border-radius: 10rpx;
      padding: 24rpx;
      box-sizing: border-box;
      margin-bottom: 24rpx;

      .top-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1rpx solid #ececec;
        padding-bottom: 26rpx;

        .lef {
          display: flex;
          align-items: center;

          .logo {
            width: 67rpx;
            height: 67rpx;
            border-radius: 50%;
            overflow: hidden;
            float: left;
          }

          .title {
            float: left;
            font-size: 32rpx;
            font-weight: bold;
            color: #181818;
            margin-left: 16rpx;
          }
        }

        .rig {
          font-size: 27rpx;
          font-weight: 500;
        }
      }

      .cen-info {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .shop {
          display: flex;
          align-items: center;

          .img {
            width: 150rpx;
            height: 150rpx;
            overflow: hidden;
            float: left;
          }
        }

        .conten {
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
          border-bottom: 1rpx solid #ececec;
          padding: 58rpx 0;
          margin-left: 16rpx;

          .shopTxt {
            .name {
              font-size: 29rpx;
              font-weight: bold;
              color: #181818;
            }

            .spec {
              margin-top: 21rpx;
              padding: 5rpx 14rpx;
              color: #888888;
              opacity: 0.8;
              font-size: 27rpx;
              border: 1px solid #b4b4b4;
              opacity: 0.8;
              border-radius: 8rpx;
              width: fit-content;
            }
          }

          .num {
            font-size: 29rpx;
            font-weight: 500;

            .money {
              color: #f05357;
              font-weight: bold;
            }

            .txt {
              color: #888888;
              text-align: right;
            }
          }
        }
      }
    }
  }

  .card-amount,
  .card-order {
    background-color: white;
    border-radius: 8rpx;
    padding: 24rpx;
    box-sizing: border-box;
    margin-top: 20rpx;

    .row {
      display: flex;
      justify-content: space-between;
      margin-top: 45rpx;
      font-size: 29rpx;
      font-weight: 500;
      color: #131313;

      .tit {
        opacity: 0.7;
      }
    }

    .row:nth-of-type(1) {
      margin-top: 0;
    }

    .results {
      display: flex;
      justify-content: flex-end;
      border-top: 1rpx solid #ececec;
      padding-top: 29rpx;

      .preferential {
        color: #888888;
        margin-right: 25rpx;
      }

      .total {
        font-weight: bold;

        span {
          color: #f05357;
        }
      }
    }
  }

  .card-order {
    margin-bottom: 150rpx;
  }

  .btm-info {
    width: 100%;
    height: 120rpx;
    display: flex;
    justify-content: space-between;
    background-color: white;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    padding: 20rpx;
    box-sizing: border-box;

    .lef {
      font-size: 29rpx;
      display: flex;
      align-items: center;

      .txt {
        float: left;
        color: #181818;
        font-weight: bold;
      }

      .money {
        float: left;
        color: #f05357;
        font-weight: bold;
        span {
          font-size: 24rpx;
        }
      }
    }

    .rig {
      display: flex;
      align-items: center;

      .payBtn,
      .againBtn {
        width: 180rpx;
        height: 80rpx;
        border-radius: 40rpx;
        font-size: 28rpx;
        font-weight: 500;
        color: #ffffff;
        text-align: center;
        line-height: 80rpx;
        float: right;
        padding: 0;
        border: 1px solid #ffffff;
        margin-left: 30rpx;
      }

      button::after {
        border: none;
      }

      .hoverClass {
        opacity: 0.5;
      }
    }
  }
}
</style>
